package com.shenzhen.horselive.ui.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.provider.ContactsContract;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.flqy.baselibrary.PhotoPagerActivity;
import com.flqy.baselibrary.utils.GlideHelper;
import com.flqy.baselibrary.utils.L;
import com.flqy.baselibrary.utils.ScreenUtil;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.shenzhen.horselive.MainActivity;
import com.shenzhen.horselive.R;
import com.shenzhen.horselive.User;
import com.shenzhen.horselive.adapter.RedCommtsAdapter;
import com.shenzhen.horselive.api.ApiFactory;
import com.shenzhen.horselive.base.AppBarActivity;
import com.shenzhen.horselive.beans.CommResponseBean;
import com.shenzhen.horselive.beans.CommResponseDataBean;
import com.shenzhen.horselive.beans.HongBaoDetailsBean;
import com.shenzhen.horselive.beans.RedCommentsBean;
import com.shenzhen.horselive.databinding.ActivityHongBaoDetailsctivityBinding;
import com.shenzhen.horselive.databinding.HeadHongbaoDetailsBinding;
import com.shenzhen.horselive.network.SchedulersCompat;
import com.shenzhen.horselive.presenter.LoadingViewObserver;
import com.shenzhen.horselive.presenter.ViewObserver;
import com.shenzhen.horselive.ui.dialog.JuBaoDialog;
import com.shenzhen.horselive.ui.dialog.MyPoupWindows;
import com.shenzhen.horselive.utils.SystemPage;

import java.util.ArrayList;
import java.util.Arrays;


/**
 * 红包的详情页面
 */
public class HongBaoDetailsActivity extends AppBarActivity {

    ActivityHongBaoDetailsctivityBinding  binding;
    private   String  tag ="2";//1是领取的，2是发送的
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        tag = getIntent().getStringExtra("tag");
        binding =  ActivityHongBaoDetailsctivityBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        setStyleRed();
        //是否是开红
        isCanBack = getIntent().getBooleanExtra("back",true);
        if (getIntent().getBooleanExtra("back",true))
        {
            //正常返回键
        }
        else
        {
            //隐藏返回键
            setNavigationText("");
        }
        setTitle("红包信息");
        setMenuIcon(R.mipmap.ico_more);
        initViews();
        initData();

    }

    RedCommtsAdapter  adapter;
    private void initViews() {
        binding.recyclerview.setLayoutManager(new LinearLayoutManager(getContext()));
        adapter = new RedCommtsAdapter(R.layout.item_comments);
        binding.recyclerview.setAdapter(adapter);
        adapter.addHeaderView(getHeadView());
        //输入框监听
        binding.etInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
              String  string =  s.toString();
              if (TextUtils.isEmpty(string))
              {
                  binding.btSend.setVisibility(View.GONE);
                  binding.tvZan.setVisibility(View.VISIBLE);
              }else
              {
                  binding.btSend.setVisibility(View.VISIBLE);
                  binding.tvZan.setVisibility(View.GONE);
              }
            }
        });

        binding.btSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendComments();
            }
        });

        binding.tvZan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //点赞或者取消赞
                sendZan();
            }
        });


        binding.smartRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                //刷新时间
                initData();
            }
        });

        binding.smartRefresh.setEnableLoadMore(false);
    }

    //红包的头部信息
    HeadHongbaoDetailsBinding  headBinding;
    private View getHeadView() {
        headBinding =  HeadHongbaoDetailsBinding.inflate(getLayoutInflater());
        return headBinding.getRoot();
    }

    private   boolean  isZaned;//是否点过赞，
    private void sendZan() {
        String  id = getIntent().getStringExtra("id");
        if (TextUtils.isEmpty(id))
        {
            return;
        }
        if (isZaned)
        {

            //取消点赞
           ApiFactory.getApiService().cancelZan(User.get().getMyInfo().getToken(),id)
                   .compose(SchedulersCompat.applyIoSchedulers())
                   .safeSubscribe(new LoadingViewObserver<CommResponseBean>(this) {
                       @Override
                       protected void onNextInActive(CommResponseBean commResponseBean) {
                           if (commResponseBean.isSuccess())
                           {
                               Drawable  drawable =getResources().getDrawable(R.mipmap.icon_zan);
                               binding.tvZan.setCompoundDrawablePadding(10);
                               binding.tvZan.setCompoundDrawablesWithIntrinsicBounds(drawable,null,null,null);
                               isZaned = false;
                               showToast("取消点赞");
                           }
                           else
                           {
                               showToast(commResponseBean.getErrMessage());
                           }
                       }
                   });
        }else
        {
            //点赞
            ApiFactory.getApiService().zan(User.get().getMyInfo().getToken(),id)
                    .compose(SchedulersCompat.applyIoSchedulers())
                    .safeSubscribe(new LoadingViewObserver<CommResponseBean>(this) {
                        @Override
                        protected void onNextInActive(CommResponseBean commResponseBean) {
                            if (commResponseBean.isSuccess())
                            {
                                Drawable  drawable =getResources().getDrawable(R.mipmap.ico_red_zan);
                                binding.tvZan.setCompoundDrawablePadding(10);
                                binding.tvZan.setCompoundDrawablesWithIntrinsicBounds(drawable,null,null,null);
                                isZaned = true;
                                 showToast("点赞成功");
                            }
                            else
                            {
                                showToast(commResponseBean.getErrMessage());
                            }
                        }
                    });
        }
    }

    //发送评论
    private void sendComments() {
        String  id = getIntent().getStringExtra("id");
        if (TextUtils.isEmpty(id))
        {
            return;
        }
        String  comment =  binding.etInput.getText().toString();
        if (TextUtils.isEmpty(comment))
        {
            showToast("请填写评论");
            return;
        }
       ApiFactory.getApiService().comment(User.get().getMyInfo().getToken()
       ,getIntent().getStringExtra("id"),comment
       ).compose(SchedulersCompat.applyIoSchedulers())
               .safeSubscribe(new LoadingViewObserver<CommResponseBean>(this) {
                   @Override
                   protected void onNextInActive(CommResponseBean commResponseBean) {
                       if (commResponseBean.isSuccess())
                       {
                          //
                           showToast("评论成功");
                           binding.etInput.setText("");
                           //更新数据
                           initData();
                       }else
                       {
                              showToast(commResponseBean.getErrMessage());
                       }
                   }
               });


    }

    private void initData() {
        //获取评论
        ApiFactory.getApiService().redCommentsList(User.get().getMyInfo().getToken(),
                getIntent().getStringExtra("id")
                ).compose(SchedulersCompat.applyIoSchedulers())
                .safeSubscribe(new LoadingViewObserver<RedCommentsBean>(this) {
                    @Override
                    protected void onNextInActive(RedCommentsBean redCommentsBean) {
                        if (binding.smartRefresh.isRefreshing())
                            binding.smartRefresh.finishRefresh();
                        if (redCommentsBean.isSuccess())
                        {
                            if (headBinding!=null)
                            {
                                headBinding.tvComments.setText(redCommentsBean.getTotal()+"");
                            }
                            adapter.setNewData(redCommentsBean.getData());
                        }else
                        {
                            showToast(redCommentsBean.getErrMessage());
                        }
                    }
                });

        //获取红包的头部信息
        ApiFactory.getApiService().redDetails(User.get().getMyInfo().getToken(),getIntent().getStringExtra("id"))
                .compose(SchedulersCompat.applyIoSchedulers())
                .safeSubscribe(new LoadingViewObserver<HongBaoDetailsBean>(this) {
                    @Override
                    protected void onNextInActive(HongBaoDetailsBean hongBaoDetailsBean) {
                        if (binding.smartRefresh.isRefreshing())
                            binding.smartRefresh.finishRefresh();
                        if (hongBaoDetailsBean.isSuccess())
                        {
                            //获取红包的返回时间
                            if (!getIntent().getBooleanExtra("back",true))
                            getBackTime(hongBaoDetailsBean.getData().getType());
                            //设置红包头部信息
                            if (headBinding!=null)
                            {
                                GlideHelper.loadAdvertImage(hongBaoDetailsBean.getData().getHeadImg(),headBinding.imgUser);
                                headBinding.tvTitle.setText(hongBaoDetailsBean.getData().getNickname());
                                headBinding.tvFanwei.setText(hongBaoDetailsBean.getData().getReceiveRangeDesc());
                                headBinding.tvZan.setText(hongBaoDetailsBean.getData().getZanNum()+"");
                                headBinding.tvCheckPeoples.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        RedPackageDetailsActivity.start(HongBaoDetailsActivity.this,getIntent().getStringExtra("id"));
                                    }
                                });

                                //是否点过赞
                                isZaned  =hongBaoDetailsBean.getData().isIsZan();
                                if (hongBaoDetailsBean.getData().isIsZan())
                                {
                                    Drawable  drawable =getResources().getDrawable(R.mipmap.ico_red_zan);
                                    binding.tvZan.setCompoundDrawablePadding(10);
                                    binding.tvZan.setCompoundDrawablesWithIntrinsicBounds(drawable,null,null,null);

                                }else
                                {
                                    Drawable  drawable =getResources().getDrawable(R.mipmap.icon_zan);
                                    binding.tvZan.setCompoundDrawablePadding(10);
                                    binding.tvZan.setCompoundDrawablesWithIntrinsicBounds(drawable,null,null,null);
                                }

                                if (hongBaoDetailsBean.getData().getHeadImgs().size()==0)
                                {
                                    //没有用户头像
                                    headBinding.containerUserHeads.setVisibility(View.GONE);
                                }
                                else
                                {
                                    headBinding.containerUserHeads.setVisibility(View.VISIBLE);
                                    headBinding.pileAvertView.setAvertImages(hongBaoDetailsBean.getData().getHeadImgs());
                                    headBinding.tvOpenPeopleNums.setText("..."+hongBaoDetailsBean.getData().getReceiveNum()+"人领取");
                                }
                                //关于红包的描述和图片
                                headBinding.tvContent.setText(hongBaoDetailsBean.getData().getDescription());
                                headBinding.tvContent.setTextIsSelectable(true);
                                headBinding.linerImgs.removeAllViews();
//                                红包的类型 1平台，2应用，3广播
                                switch (Integer.parseInt(hongBaoDetailsBean.getData().getType()))
                                {
                                    case 1:
                                    case 3:
                                        for (int i = 0; i < hongBaoDetailsBean.getData().getPics().size(); i++) {
                                            ImageView  imageView = new ImageView(HongBaoDetailsActivity.this);
                                            LinearLayout.LayoutParams  layoutParams = new LinearLayout.LayoutParams(ScreenUtil.dip2px(97), ViewGroup.LayoutParams.MATCH_PARENT);
                                            if (i!=0)
                                                layoutParams.leftMargin = ScreenUtil.dip2px(17);
                                            imageView.setLayoutParams(layoutParams);
                                            //加载图片
                                            String  url = hongBaoDetailsBean.getData().getPics().get(i);
                                            GlideHelper.loadRoundImage(imageView,url);
                                            headBinding.linerImgs.addView(imageView);
                                            imageView.setOnClickListener(new View.OnClickListener() {
                                                @Override
                                                public void onClick(View v) {
                                                    PhotoPagerActivity.launch(HongBaoDetailsActivity.this,url);

                                                }
                                            });
                                        }
                                        break;
                                    case 2:
                                        //应用红包
                                        LayoutInflater.from(HongBaoDetailsActivity.this)
                                                .inflate(R.layout.head_item_hongbao_details_app,headBinding.linerImgs);
                                        GlideHelper.loadRoundImage(headBinding.linerImgs.findViewById(R.id.img_app),hongBaoDetailsBean.getData().getApplicationInfo().getApplicationLogo());
                                        TextView  textView = headBinding.linerImgs.findViewById(R.id.tv_name);
                                        TextView  textView1 = headBinding.linerImgs.findViewById(R.id.tv_content);
                                        textView.setText(hongBaoDetailsBean.getData().getApplicationInfo().getApplicationName());
                                        textView1.setText(hongBaoDetailsBean.getData().getApplicationInfo().getApplicationDesc());
                                        //应用查看按钮
                                        ImageView  imageView =  headBinding.linerImgs.findViewById(R.id.img_bianji);
                                        imageView.setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                //跳转系统浏览器
                                                SystemPage.startWeb(HongBaoDetailsActivity.this,hongBaoDetailsBean.getData().getApplicationInfo().getApplicationUrl());
                                            }
                                        });
                                        break;
                                }
                                //区分发送的和领取的红包
                                if ("1".equals(tag))
                                {
                                    //领取红包
                                    headBinding.groupGetMoney.setVisibility(View.VISIBLE);
                                    headBinding.tvLeftRedNums.setVisibility(View.GONE);
                                    //领取到的金额和红包股
                                    headBinding.tvRedGu.setText("￥"+hongBaoDetailsBean.getData().getReceiveAmount());
                                    headBinding.tvGetMoney.setText(hongBaoDetailsBean.getData().getReceiveShares()+"红包股");
                                }
                                else {
                                    //发出去的红包
                                    headBinding.groupGetMoney.setVisibility(View.GONE);
                                    headBinding.tvLeftRedNums.setVisibility(View.VISIBLE);
                                    //剩余的红包
                                    if (hongBaoDetailsBean.getData().getResidueNum()==0)
                                    {
                                        headBinding.tvLeftRedNums.setText("手慢了，红包派完了");
                                    }
                                    else
                                    {
                                        headBinding.tvLeftRedNums.setText(hongBaoDetailsBean.getData().getResidueNum()+"个红包待领取");
                                    }
                                }










                            }

                        }else
                        {
                            showToast(hongBaoDetailsBean.getErrMessage());
                        }
                    }
                });



    }



    CountDownTimer  countDownTimer;
    /**
     * 获取红包的事件
     * @param redEnvelopesType  红包的类型
     */
    private void getBackTime(String redEnvelopesType) {
        ApiFactory.getApiService().hongbaoTime(User.get().getMyInfo().getToken(),redEnvelopesType)
                .compose(SchedulersCompat.applyIoSchedulers())
                .safeSubscribe(new LoadingViewObserver<CommResponseDataBean>(this) {
                    @Override
                    protected void onNextInActive(CommResponseDataBean commResponseDataBean) {
                        if (commResponseDataBean.isSuccess())
                        {
                            String  data =  commResponseDataBean.getData();
                            if (countDownTimer!=null)
                            {
                                countDownTimer.cancel();
                            }
                            countDownTimer =  new CountDownTimer(Integer.parseInt(data)*1000,1000) {
                                @Override
                                public void onTick(long millisUntilFinished) {
                                    setNavigationText(millisUntilFinished/1000+"");
                                }

                                @Override
                                public void onFinish() {
                                    isCanBack  =true;
                                    setNavigationIcon(R.mipmap.ico_back);

                                }
                            };
                            countDownTimer.start();


                        }
                    }
                });
    }

    MyPoupWindows  myPoupWindows;
    JuBaoDialog  juBaoDialog;
    @Override
    protected void onActionMenuViewClick() {
        super.onActionMenuViewClick();
        if (myPoupWindows==null)
        {
         myPoupWindows = new MyPoupWindows(this);
         myPoupWindows.setOnJubaoClick(new MyPoupWindows.OnJubaoClick() {
             @Override
             public void OnClick() {
                 //底部弹窗
                 if (juBaoDialog==null)
                 {
                     juBaoDialog = new JuBaoDialog(HongBaoDetailsActivity.this);
                     String[]  strings = {"淫秽色情","政治反动","恶意谩骂","违法犯罪","虚假信息","其他",};
                     juBaoDialog.setList(Arrays.asList(strings));
                     juBaoDialog.setOnItemClick(new OnItemClickListener() {
                         @Override
                         public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                             String  string = (String) adapter.getData().get(position);
                             jubao(string);
                             juBaoDialog.dismiss();
                         }
                     });
                 }
                 juBaoDialog.show();
             }
         });
        }
        myPoupWindows.showAsDropDown(getToolbar(),0,0,Gravity.RIGHT);

    }

    //举报红包
    private void jubao(String string) {
        if (TextUtils.isEmpty(string))
        {
            return;
        }
        ApiFactory.getApiService().juBao(User.get().getMyInfo().getToken(),
                getIntent().getStringExtra("id"),string
                )
                .compose(SchedulersCompat.applyIoSchedulers())
                .safeSubscribe(new LoadingViewObserver<CommResponseBean>(this) {
                    @Override
                    protected void onNextInActive(CommResponseBean commResponseBean) {
                        if (commResponseBean.isSuccess())
                        {
                           showToast("举报成功");
                        }
                        else {
                            showToast(commResponseBean.getErrMessage());
                        }
                    }
                });
    }

    public static void start(Context context, String tag, String  id) {
        Intent starter = new Intent(context, HongBaoDetailsActivity.class);
        starter.putExtra("tag",tag);
        starter.putExtra("id",id);
        context.startActivity(starter);
    }
    public static void start(Context context, String tag, String  id,boolean  canGoback) {
        Intent starter = new Intent(context, HongBaoDetailsActivity.class);
        starter.putExtra("tag",tag);
        starter.putExtra("id",id);
        starter.putExtra("back",canGoback);
        context.startActivity(starter);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode==KeyEvent.KEYCODE_BACK&&!isCanBack)
        {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countDownTimer!=null)
        {
            countDownTimer.cancel();
            countDownTimer = null;
        }
    }


    boolean  isCanBack =true;
    @Override
    protected void onNavigationViewClick() {
        if (!isCanBack)
            return;
        super.onNavigationViewClick();
    }
}